#include "histogramRGB.h"
#include <iostream>

HistogramRGB::HistogramRGB(): Histogram()
{
    histogramR=new unsigned int[256];
    histogramG=new unsigned int[256];
    histogramB=new unsigned int[256];
    redCDF= new unsigned long[256];
    greenCDF= new unsigned long[256];
    blueCDF = new unsigned long[256];
}

HistogramRGB::HistogramRGB(QImage* mi): Histogram(mi)
{
    histogramR=new unsigned int[256];
    histogramG=new unsigned int[256];
    histogramB=new unsigned int[256];
    redCDF= new unsigned long[256];
    greenCDF= new unsigned long[256];
    blueCDF = new unsigned long[256];
}

HistogramRGB::~HistogramRGB()
{
    delete []histogramR;
    delete []histogramG;
    delete []histogramB;
}

void HistogramRGB::calcHistogram()
{
    if(ownerImage==NULL)
        return;
    else
    {
        for(int i=0;i<256;i++)
        {
            histogramR[i]=0;
            histogramG[i]=0;
            histogramB[i]=0;
        }
        for(int x=0;x<ownerImage->width();x++)
            for(int y=0;y<ownerImage->height();y++)
            {
                histogramR[qRed(ownerImage->pixel(x,y))]++;
                histogramG[qGreen(ownerImage->pixel(x,y))]++;
                histogramB[qBlue(ownerImage->pixel(x,y))]++;
            }
            calcHistImage();
    }
}

void HistogramRGB::calcHistImage()
{
    if(histImage==NULL)
        histImage=new QImage(256,100,QImage::Format_RGB32);
    unsigned long max=0;
    for(int i=0;i<256;i++)
    {
        if(histogramR[i]>max)
            max=histogramR[i];
        if(histogramG[i]>max)
            max=histogramG[i];
        if(histogramB[i]>max)
            max=histogramB[i];
    }
    std::cout << max << std::endl;
    for(int x=0;x<histImage->width();x++)
        for(int y=0;y<histImage->height();y++)
            histImage->setPixel(x,y,qRgb(0,0,0));
    for(int i=0;i<256;i++)
    {
        histImage->setPixel(i,99-(int)(histogramR[i]/(double)max*99),qRgb(255,0,0));
        histImage->setPixel(i,99-(int)(histogramG[i]/(double)max*99),qRgb(0,255,0));
        histImage->setPixel(i,99-(int)(histogramB[i]/(double)max*99),qRgb(0,0,255));
    }
}
 void  HistogramRGB ::calcCDF()
{
     for(int i=0;i<256;i++)
     {
         redCDF[i]=0;
         greenCDF[i]=0;
         blueCDF[i]=0;
     }
     for(int i=0;i<256;i++)
     {
         for(int j=0;j<=i;j++)
         {
             redCDF[i]=this->histogramR[j]+redCDF[i];
             greenCDF[i]=this->histogramG[j]+greenCDF[i];
             blueCDF[i]=this->histogramB[j]+greenCDF[i];
         }
     }
}
 unsigned long * HistogramRGB::getBlueCDF()
 {
     return this->blueCDF;
 }
 unsigned long * HistogramRGB::getRedCDF()
 {
     return this->redCDF;
 }
 unsigned long * HistogramRGB::getGreenCDF()
 {
     return this->greenCDF;
 }

